{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 多GPU计算\n",
    "\n",
    "本节中我们将展示如何使用多块GPU计算，例如，使用多块GPU训练同一个模型。正如所期望的那样，运行本节中的程序需要至少2块GPU。事实上，一台机器上安装多块GPU很常见，这是因为主板上通常会有多个PCIe插槽。如果正确安装了NVIDIA驱动，我们可以通过`nvidia-smi`命令来查看当前计算机上的全部GPU。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "1"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Fri Nov  1 08:12:14 2019       \r\n",
      "+-----------------------------------------------------------------------------+\r\n",
      "| NVIDIA-SMI 418.67       Driver Version: 418.67       CUDA Version: 10.1     |\r\n",
      "|-------------------------------+----------------------+----------------------+\r\n",
      "| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |\r\n",
      "| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |\r\n",
      "|===============================+======================+======================|\r\n",
      "|   0  Tesla V100-SXM2...  Off  | 00000000:00:1B.0 Off |                    0 |\r\n",
      "| N/A   61C    P0    60W / 300W |      0MiB / 16130MiB |      0%      Default |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "|   1  Tesla V100-SXM2...  Off  | 00000000:00:1C.0 Off |                    0 |\r\n",
      "| N/A   50C    P0    56W / 300W |      0MiB / 16130MiB |      0%      Default |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "|   2  Tesla V100-SXM2...  Off  | 00000000:00:1D.0 Off |                    0 |\r\n",
      "| N/A   45C    P0    57W / 300W |      0MiB / 16130MiB |      0%      Default |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "|   3  Tesla V100-SXM2...  Off  | 00000000:00:1E.0 Off |                    0 |\r\n",
      "| N/A   45C    P0    56W / 300W |      0MiB / 16130MiB |      4%      Default |\r\n",
      "+-------------------------------+----------------------+----------------------+\r\n",
      "                                                                               \r\n",
      "+-----------------------------------------------------------------------------+\r\n",
      "| Processes:                                                       GPU Memory |\r\n",
      "|  GPU       PID   Type   Process name                             Usage      |\r\n",
      "|=============================================================================|\r\n",
      "|  No running processes found                                                 |\r\n",
      "+-----------------------------------------------------------------------------+\r\n"
     ]
    }
   ],
   "source": [
    "!nvidia-smi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[“自动并行计算”](auto-parallelism.ipynb)一节介绍过，大部分运算可以使用所有的CPU的全部计算资源，或者单块GPU的全部计算资源。但如果使用多块GPU训练模型，我们仍然需要实现相应的算法。这些算法中最常用的叫作数据并行。\n",
    "\n",
    "\n",
    "## 数据并行\n",
    "\n",
    "数据并行目前是深度学习里使用最广泛的将模型训练任务划分到多块GPU的方法。回忆一下我们在[“小批量随机梯度下降”](../chapter_optimization/minibatch-sgd.ipynb)一节中介绍的使用优化算法训练模型的过程。下面我们就以小批量随机梯度下降为例来介绍数据并行是如何工作的。\n",
    "\n",
    "假设一台机器上有$k$块GPU。给定需要训练的模型，每块GPU及其相应的显存将分别独立维护一份完整的模型参数。在模型训练的任意一次迭代中，给定一个随机小批量，我们将该批量中的样本划分成$k$份并分给每块显卡的显存一份。然后，每块GPU将根据相应显存所分到的小批量子集和所维护的模型参数分别计算模型参数的本地梯度。接下来，我们把$k$块显卡的显存上的本地梯度相加，便得到当前的小批量随机梯度。之后，每块GPU都使用这个小批量随机梯度分别更新相应显存所维护的那一份完整的模型参数。图8.1描绘了使用2块GPU的数据并行下的小批量随机梯度的计算。\n",
    "\n",
    "![使用2块GPU的数据并行下的小批量随机梯度的计算](../img/data-parallel.svg)\n",
    "\n",
    "为了从零开始实现多GPU训练中的数据并行，让我们先导入需要的包或模块。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "2"
    }
   },
   "outputs": [],
   "source": [
    "import d2lzh as d2l\n",
    "import mxnet as mx\n",
    "from mxnet import autograd, nd\n",
    "from mxnet.gluon import loss as gloss\n",
    "import time"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义模型\n",
    "\n",
    "我们使用[“卷积神经网络（LeNet）”](../chapter_convolutional-neural-networks/lenet.ipynb)一节里介绍的LeNet来作为本节的样例模型。这里的模型实现部分只用到了`NDArray`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "3"
    }
   },
   "outputs": [],
   "source": [
    "# 初始化模型参数\n",
    "scale = 0.01\n",
    "W1 = nd.random.normal(scale=scale, shape=(20, 1, 3, 3))\n",
    "b1 = nd.zeros(shape=20)\n",
    "W2 = nd.random.normal(scale=scale, shape=(50, 20, 5, 5))\n",
    "b2 = nd.zeros(shape=50)\n",
    "W3 = nd.random.normal(scale=scale, shape=(800, 128))\n",
    "b3 = nd.zeros(shape=128)\n",
    "W4 = nd.random.normal(scale=scale, shape=(128, 10))\n",
    "b4 = nd.zeros(shape=10)\n",
    "params = [W1, b1, W2, b2, W3, b3, W4, b4]\n",
    "\n",
    "# 定义模型\n",
    "def lenet(X, params):\n",
    "    h1_conv = nd.Convolution(data=X, weight=params[0], bias=params[1],\n",
    "                             kernel=(3, 3), num_filter=20)\n",
    "    h1_activation = nd.relu(h1_conv)\n",
    "    h1 = nd.Pooling(data=h1_activation, pool_type='avg', kernel=(2, 2),\n",
    "                    stride=(2, 2))\n",
    "    h2_conv = nd.Convolution(data=h1, weight=params[2], bias=params[3],\n",
    "                             kernel=(5, 5), num_filter=50)\n",
    "    h2_activation = nd.relu(h2_conv)\n",
    "    h2 = nd.Pooling(data=h2_activation, pool_type='avg', kernel=(2, 2),\n",
    "                    stride=(2, 2))\n",
    "    h2 = nd.flatten(h2)\n",
    "    h3_linear = nd.dot(h2, params[4]) + params[5]\n",
    "    h3 = nd.relu(h3_linear)\n",
    "    y_hat = nd.dot(h3, params[6]) + params[7]\n",
    "    return y_hat\n",
    "\n",
    "# 交叉熵损失函数\n",
    "loss = gloss.SoftmaxCrossEntropyLoss()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 多GPU之间同步数据\n",
    "\n",
    "我们需要实现一些多GPU之间同步数据的辅助函数。下面的`get_params`函数将模型参数复制到某块显卡的显存并初始化梯度。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "4"
    }
   },
   "outputs": [],
   "source": [
    "def get_params(params, ctx):\n",
    "    new_params = [p.copyto(ctx) for p in params]\n",
    "    for p in new_params:\n",
    "        p.attach_grad()\n",
    "    return new_params"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "尝试把模型参数`params`复制到`gpu(0)`上。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "5"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b1 weight: \n",
      "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      "<NDArray 20 @gpu(0)>\n",
      "b1 grad: \n",
      "[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n",
      "<NDArray 20 @gpu(0)>\n"
     ]
    }
   ],
   "source": [
    "new_params = get_params(params, mx.gpu(0))\n",
    "print('b1 weight:', new_params[1])\n",
    "print('b1 grad:', new_params[1].grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "给定分布在多块显卡的显存之间的数据。下面的`allreduce`函数可以把各块显卡的显存上的数据加起来，然后再广播到所有的显存上。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "6"
    }
   },
   "outputs": [],
   "source": [
    "def allreduce(data):\n",
    "    for i in range(1, len(data)):\n",
    "        data[0][:] += data[i].copyto(data[0].context)\n",
    "    for i in range(1, len(data)):\n",
    "        data[0].copyto(data[i])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "简单测试一下`allreduce`函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "7"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "before allreduce: [\n",
      "[[1. 1.]]\n",
      "<NDArray 1x2 @gpu(0)>, \n",
      "[[2. 2.]]\n",
      "<NDArray 1x2 @gpu(1)>]\n",
      "after allreduce: [\n",
      "[[3. 3.]]\n",
      "<NDArray 1x2 @gpu(0)>, \n",
      "[[3. 3.]]\n",
      "<NDArray 1x2 @gpu(1)>]\n"
     ]
    }
   ],
   "source": [
    "data = [nd.ones((1, 2), ctx=mx.gpu(i)) * (i + 1) for i in range(2)]\n",
    "print('before allreduce:', data)\n",
    "allreduce(data)\n",
    "print('after allreduce:', data)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "给定一个批量的数据样本，下面的`split_and_load`函数可以将其划分并复制到各块显卡的显存上。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "8"
    }
   },
   "outputs": [],
   "source": [
    "def split_and_load(data, ctx):\n",
    "    n, k = data.shape[0], len(ctx)\n",
    "    m = n // k  # 简单起见，假设可以整除\n",
    "    assert m * k == n, '# examples is not divided by # devices.'\n",
    "    return [data[i * m: (i + 1) * m].as_in_context(ctx[i]) for i in range(k)]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "让我们试着用`split_and_load`函数将6个数据样本平均分给2块显卡的显存。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "9"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input:  \n",
      "[[ 0.  1.  2.  3.]\n",
      " [ 4.  5.  6.  7.]\n",
      " [ 8.  9. 10. 11.]\n",
      " [12. 13. 14. 15.]\n",
      " [16. 17. 18. 19.]\n",
      " [20. 21. 22. 23.]]\n",
      "<NDArray 6x4 @cpu(0)>\n",
      "load into [gpu(0), gpu(1)]\n",
      "output: [\n",
      "[[ 0.  1.  2.  3.]\n",
      " [ 4.  5.  6.  7.]\n",
      " [ 8.  9. 10. 11.]]\n",
      "<NDArray 3x4 @gpu(0)>, \n",
      "[[12. 13. 14. 15.]\n",
      " [16. 17. 18. 19.]\n",
      " [20. 21. 22. 23.]]\n",
      "<NDArray 3x4 @gpu(1)>]\n"
     ]
    }
   ],
   "source": [
    "batch = nd.arange(24).reshape((6, 4))\n",
    "ctx = [mx.gpu(0), mx.gpu(1)]\n",
    "splitted = split_and_load(batch, ctx)\n",
    "print('input: ', batch)\n",
    "print('load into', ctx)\n",
    "print('output:', splitted)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 单个小批量上的多GPU训练\n",
    "\n",
    "现在我们可以实现单个小批量上的多GPU训练了。它的实现主要依据本节介绍的数据并行方法。我们将使用刚刚定义的多GPU之间同步数据的辅助函数`allreduce`和`split_and_load`。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "10"
    }
   },
   "outputs": [],
   "source": [
    "def train_batch(X, y, gpu_params, ctx, lr):\n",
    "    # 当ctx包含多块GPU及相应的显存时，将小批量数据样本划分并复制到各个显存上\n",
    "    gpu_Xs, gpu_ys = split_and_load(X, ctx), split_and_load(y, ctx) \n",
    "    with autograd.record():  # 在各块GPU上分别计算损失\n",
    "        ls = [loss(lenet(gpu_X, gpu_W), gpu_y)\n",
    "              for gpu_X, gpu_y, gpu_W in zip(gpu_Xs, gpu_ys, gpu_params)]\n",
    "    for l in ls:  # 在各块GPU上分别反向传播\n",
    "        l.backward()\n",
    "    # 把各块显卡的显存上的梯度加起来，然后广播到所有显存上\n",
    "    for i in range(len(gpu_params[0])):\n",
    "        allreduce([gpu_params[c][i].grad for c in range(len(ctx))])\n",
    "    for param in gpu_params:  # 在各块显卡的显存上分别更新模型参数\n",
    "        d2l.sgd(param, lr, X.shape[0])  # 这里使用了完整批量大小"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 定义训练函数\n",
    "\n",
    "现在我们可以定义训练函数了。这里的训练函数和[“softmax回归的从零开始实现”](../chapter_deep-learning-basics/softmax-regression-scratch.ipynb)一节定义的训练函数`train_ch3`有所不同。值得强调的是，在这里我们需要依据数据并行将完整的模型参数复制到多块显卡的显存上，并在每次迭代时对单个小批量进行多GPU训练。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "11"
    }
   },
   "outputs": [],
   "source": [
    "def train(num_gpus, batch_size, lr):\n",
    "    train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)\n",
    "    ctx = [mx.gpu(i) for i in range(num_gpus)]\n",
    "    print('running on:', ctx)\n",
    "    # 将模型参数复制到num_gpus块显卡的显存上\n",
    "    gpu_params = [get_params(params, c) for c in ctx]\n",
    "    for epoch in range(4):\n",
    "        start = time.time()\n",
    "        for X, y in train_iter:\n",
    "            # 对单个小批量进行多GPU训练\n",
    "            train_batch(X, y, gpu_params, ctx, lr)\n",
    "            nd.waitall()\n",
    "        train_time = time.time() - start\n",
    "\n",
    "        def net(x):  # 在gpu(0)上验证模型\n",
    "            return lenet(x, gpu_params[0])\n",
    "\n",
    "        test_acc = d2l.evaluate_accuracy(test_iter, net, ctx[0])\n",
    "        print('epoch %d, time %.1f sec, test acc %.2f'\n",
    "              % (epoch + 1, train_time, test_acc))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 多GPU训练实验\n",
    "\n",
    "让我们先从单GPU训练开始。设批量大小为256，学习率为0.2。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "12"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "running on: [gpu(0)]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, time 1.6 sec, test acc 0.10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, time 1.4 sec, test acc 0.56\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, time 1.4 sec, test acc 0.75\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, time 1.5 sec, test acc 0.72\n"
     ]
    }
   ],
   "source": [
    "train(num_gpus=1, batch_size=256, lr=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "保持批量大小和学习率不变，将使用的GPU数量改为2。可以看到，测试精度的提升同上一个实验中的结果大体相当。因为有额外的通信开销，所以我们并没有看到训练时间的显著降低。因此，我们将在下一节实验计算更加复杂的模型。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "attributes": {
     "classes": [],
     "id": "",
     "n": "13"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "running on: [gpu(0), gpu(1)]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, time 2.7 sec, test acc 0.10\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, time 2.5 sec, test acc 0.69\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, time 2.6 sec, test acc 0.75\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, time 2.5 sec, test acc 0.75\n"
     ]
    }
   ],
   "source": [
    "train(num_gpus=2, batch_size=256, lr=0.2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 小结\n",
    "\n",
    "* 可以使用数据并行更充分地利用多块GPU的计算资源，实现多GPU训练模型。\n",
    "* 给定超参数的情况下，改变GPU数量时模型的训练精度大体相当。\n",
    "\n",
    "## 练习\n",
    "\n",
    "* 在多GPU训练实验中，使用2块GPU训练并将`batch_size`翻倍至512，训练时间有何变化？如果希望测试精度与单GPU训练中的结果相当，学习率应如何调节？\n",
    "* 将实验的模型预测部分改为用多GPU预测。\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "## 扫码直达[讨论区](https://discuss.gluon.ai/t/topic/1884)\n",
    "\n",
    "![](../img/qr_multiple-gpus.svg)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}